package com.ctg.behavior.calc.controller.attribution;

import java.io.InputStream;
import java.util.List;
import java.util.Random;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.common.attribution.CtAttributionCalcRequest;
import com.ctg.behavior.common.attribution.CtAttributionCalcResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api/attribution")
public class AttributionController {

    @Value("${simulator.path}")
    private String simlutorPath;

    @PostMapping("/report")
    public CtAttributionCalcResult report(@RequestBody CtAttributionCalcRequest request) throws Exception {

        CtAttributionCalcResult result = new CtAttributionCalcResult();
        log.info("request", JSON.toJSONString(request));

        // 检查文件并读取文件
        ClassPathResource classPathResource = null;
        Random random = new Random();
        if (random.nextBoolean()) {
            classPathResource = new ClassPathResource("attribute/report/attribute.json");
        } else {
            classPathResource = new ClassPathResource("attribute/report/attribute_byValue.json");
        }

        InputStream inputStream = classPathResource.getInputStream();
        List<String> lines = IOUtils.readLines(inputStream, "UTF-8");
        StringBuilder sbuilder = new StringBuilder();
        for (String line : lines) {
            sbuilder.append(line);
        }
        result = JSON.parseObject(sbuilder.toString(), CtAttributionCalcResult.class);


        log.info("result", JSON.toJSONString(result));

        return result;
    }


}
